package com.xdxc.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xdxc.model.bo.UserAnswerWithGrading;
import com.xdxc.model.entity.TempUserAnswer;
import com.xdxc.model.vo.UserAnswerVo;
import com.xdxc.utils.JsonTypeHandler;

import org.apache.ibatis.annotations.*;

import java.math.BigDecimal;
import java.util.List;

@Mapper
public interface TempUserAnswerMapper extends BaseMapper<TempUserAnswer> {
    @Options(useGeneratedKeys = false, flushCache = Options.FlushCachePolicy.TRUE)
    @Update("<script>" +
            "INSERT INTO temp_user_answer " +
            "(id, paper_id, qu_id, answer_type, answer_ids, answer_text, version, user_id,exam_id,check_id) " +
            "VALUES " +
            "<foreach collection='list' item='item' separator=','>" +
            "(#{item.id}, #{item.paperId}, #{item.quId}, #{item.answerType}, " +
            "#{item.answerIds, typeHandler=com.xdxc.utils.JsonTypeHandler}, " +
            "#{item.answerText}, " +
            "#{item.version}, #{item.userId}, #{item.examId}, #{item.checkId})" +
            "</foreach>" +
            "ON DUPLICATE KEY UPDATE " +
            "answer_ids = VALUES(answer_ids), " +
            "answer_text = VALUES(answer_text), " +
            "version = version + 1, " +
            "update_time = NOW()" +
            "</script>")
    int batchUpsert(@Param("list") List<TempUserAnswer> list);

    // 新增：按主键排序的批量更新（防止死锁）
    @Update("<script>" +
            "INSERT INTO temp_user_answer " +
            "(id, paper_id, qu_id, answer_type, answer_ids, answer_text, answer_files, version, is_deleted, update_time, answer_type_text, user_id) " +
            "VALUES " +
            "<foreach collection='list' item='entity' separator=','>" +
            "(#{entity.id}, #{entity.paperId}, #{entity.quId}, #{entity.answerType}, " +
            "#{entity.answerIds, typeHandler=com.xdxc.utils.JsonTypeHandler}, " +
            "#{entity.answerText}, " +
            "#{entity.answerFiles, typeHandler=com.xdxc.utils.JsonTypeHandler}, " +
            "#{entity.version}, #{entity.isDeleted}, " +
            "NOW(), #{entity.answerTypeText}, #{entity.userId})" +
            "</foreach>" +
            "ON DUPLICATE KEY UPDATE " +
            "answer_ids = VALUES(answer_ids), " +
            "answer_text = VALUES(answer_text), " +
            "answer_files = VALUES(answer_files), " +
            "version = VALUES(version) + 1, " +
            "is_deleted = VALUES(is_deleted), " +
            "update_time = NOW(), " +
            "answer_type_text = VALUES(answer_type_text), " +
            "user_id = VALUES(user_id)" +
            "</script>")
    void batchUpsertOrdered(@Param("list") List<TempUserAnswer> entities);


    @Select("<script>" +
            "SELECT " +
            "  ua.id AS user_answer_id, " +
            "  ua.paper_id, " +
            "  ua.qu_id, " +
            "  ua.answer_type, " +
            "  ua.answer_ids, " +
            "  ua.answer_text, " +
            "  ua.check_id, " +
            "  gr.id AS grading_id, " +
            "  gr.answer_id AS grading_answer_id, " +
            "  gr.is_correct AS grading_is_correct, " +
            "  gr.user_score AS grading_user_score, " +
            "  gr.details AS grading_details, " +
            "  gr.rule_version AS grading_rule_version, " +
            "  gr.paper_id AS grading_paper_id, " +
            "  CASE WHEN gr.user_score IS NOT NULL THEN CONCAT(gr.user_score, '分') ELSE '未评分' END AS formatted_score " +
            "FROM temp_user_answer ua " +
            "LEFT JOIN grading_result gr ON ua.id = gr.answer_id " +
            "WHERE ua.paper_id = #{paperId} " +
            "ORDER BY ua.create_time DESC" +
            "</script>")
    @Results(id = "userAnswerVoMap", value = {
            // 基础字段
            @Result(column = "user_answer_id", property = "id"),
            @Result(column = "paper_id", property = "paperId"),
            @Result(column = "qu_id", property = "quId"),
            @Result(column = "answer_type", property = "answerType"),
            @Result(column = "answer_ids", property = "answerIds", typeHandler = JsonTypeHandler.class),
            @Result(column = "answer_text", property = "answerText"),
            @Result(column = "check_id", property = "checkId"),
            @Result(column = "formatted_score", property = "formattedScore"),

            // GradingResultDTO映射
            @Result(column = "grading_id", property = "gradingResultDTO.id"),
            @Result(column = "grading_answer_id", property = "gradingResultDTO.answerId"),
            @Result(column = "grading_is_correct", property = "gradingResultDTO.isCorrect"),
            @Result(column = "grading_user_score", property = "gradingResultDTO.userScore",
                    javaType = BigDecimal.class),
            @Result(column = "grading_details", property = "gradingResultDTO.details"),
            @Result(column = "grading_rule_version", property = "gradingResultDTO.ruleVersion"),
            @Result(column = "grading_paper_id", property = "gradingResultDTO.paperId")
    })
    List<UserAnswerVo> selectByPaperIdWithGrading(@Param("paperId") Long paperId);
}
